<?php

namespace common\models;

use Yii;
use yii\helpers\ArrayHelper;

class AdminRole extends ActiveRecord {

    // only define rules for those attributes that
    // will receive user inputs.
    public function rules()
    {
        return [
            [['title', 'identify'], 'required'],
            [['sort', 'deleted_at'], 'integer'],
            [['title', 'identify'], 'string', 'max' => 128],
            [['identify'], 'match', 'pattern' => "/^[\w\-\_\.]+$/"],
            [['remark'], 'string', 'max' => 255]
        ];
    }
    /**
     * @name 字段名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'title' => '名称',
            'identify' => '标识',
            'sort' => '排序',
            'remark' => '备注',
            'deleted_at' => '删除时间',
        ];
    }

    /**
     * @name update & insert data check config for html
     * @param $type string 页面操作类型
     * @param $encodeJson boolean 是否转成json串
     * @return string | array
     */
    public static function flyer($type = 'update')
    {
        $rule = [
            'param' => [
                'title' => ['权组名称', ['maxlength' => 128, 'required']],
                'identify' => ['标识', ['preg' => '/^[\w\-_\.]{1,}$/', 'required']],
                'remark' => ['描述', ['maxlength' => 255]],
            ]
        ];
        return $rule;
    }

    /**
     * @name find permissions list
     * @return object list
     */
    public function getRolePermissions()
    {
        return $this->hasMany(AdminPermission::className(), ['identify' => 'identify']);
    }

    // @name 修改navigator.controller时
    // @describe 需要更新admin_navigator的navigator_path字段
    // @param $old_identify string 老的权限标识
    // @rturn boolean
    public function onChange($old_identify)
    {
        if($this->identify && ($this->identify != $old_identify)) {
            return AdminPermission::updateAll(['identify' => $this->identify], ['identify' => $old_identify]);
        }
        return true;
    }

    /**
     * @name change admin's permission
     * @param $role_id int  - role id
     * @param $permissions array  - permission details (navigator's id)
     * @return array [code, message]
     */
    public function setPermissions($permissions)
    {
        // echo '<pre>parent: '; print_r($permissions); echo '</pre>'; die;
        // 搜索当前选中的权限
        $new_permissions = [];
        if($permissions) {
            $navigators = Navigator::find()->where(['id' => $permissions])->with('parent')->orderBy('id ASC')->all();
            // echo '<pre>'; print_r($navigators); echo '</pre>'; die;
            if(count($navigators)) {
                foreach($navigators as $navigator) {
                    // echo '<pre>'; print_r($navigator); echo '</pre>';
                    $controller = $navigator->controller;
                    // echo '<pre>'; print_r($controller); echo '</pre>';
                    if($navigator->parent_id == 0) {
                        // 子栏目超级权限
                        $new_permissions[$controller .'~'] = true;
                    }
                    else {
                        // 如果存在子菜单超级权限 则不记录此菜单下的所有子菜单
                        // echo '<pre>parent: '; print_r($parent); echo '</pre>'; die;
                        if( ! $navigator->parent || isset($new_permissions[$navigator->parent->controller .'~'])) {
                            continue;
                        }
                        $new_permissions[$navigator->parent->controller .'~'. $controller] = true;
                    }
                }
            }
        }
        // echo '<pre>'; print_r($new_permissions); echo '</pre>';
        // 查询当前权组拥有的权限，进行去重、删除以剔除权限
        $cur_permissions = $this->getRolePermissions()->asArray()->all();
        // echo '<pre>cur: '; print_r($cur_permissions); echo '</pre>';
        // echo '<pre>new: '; print_r($new_permissions); echo '</pre>'; die;
        if($cur_permissions) {
            foreach($cur_permissions as $permission) {
                // echo '<pre>'; print_r($permission->navigator_path); echo '</pre>';
                // 如果当前已经拥有此选中权限， 则从选中权限中剔除
                if(isset($new_permissions[$permission['navigator_path']])) {
                    unset($new_permissions[$permission['navigator_path']]);
                }
                // 否则添加到删除数组中
                else {
                    $delete_permission[] = $permission;
                }
                // echo '<pre>'; print_r($new_permissions); echo '</pre>';
            }
        }
        // echo '<pre>'; print_r($new_permissions); echo '</pre>'; die;
        // echo '<pre>'; print_r($delete_permission); echo '</pre>'; die;
        if(isset($delete_permission)) {
            foreach($delete_permission as $permission) {
                if( ! AdminPermission::deleteAll(['identify' => ArrayHelper::getColumn($delete_permission, 'identify')])) {
                    return ['code' => 'System.Error', 'message' => '删除权限失败（System.Error）'];
                }
            }
        }
        // echo '<pre>'; print_r($delete_permission); echo '</pre>'; die;
        if(count($new_permissions) > 0) {
            $date = time();
            foreach($new_permissions as $navigator_path => $t) {
                $param[] = [$this->identify, $navigator_path, $date, $date];
            }
            if( ! Yii::$app->db->createCommand()->batchInsert('admin_permission', ['identify', 'navigator_path', 'created_at', 'updated_at'], $param)->execute()) {
                return ['code' => 'System.Error', 'message' => '权限添加失败'];
            }
        }
        return ['code' => 200, 'message' => ''];
    }

    // @name for select use
    // @return array relation of[id => title]
    public static function getRolesForSelect()
    {
        return ArrayHelper::map(self::find()->select('id, title')->orderBy('id ASC')->asArray()->all(), 'id', 'title');
    }
}